filters.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  1. """Built-in template filters used with the ``|`` operator."""
  2. import math
  3. import random
  4. import re
  5. import typing
  6. import typing as t
  7. from collections import abc
  8. from itertools import chain
  9. from itertools import groupby
  10. from markupsafe import escape
  11. from markupsafe import Markup
  12. from markupsafe import soft_str
  13. from .async_utils import async_variant
  14. from .async_utils import auto_aiter
  15. from .async_utils import auto_await
  16. from .async_utils import auto_to_list
  17. from .exceptions import FilterArgumentError
  18. from .runtime import Undefined
  19. from .utils import htmlsafe_json_dumps
  20. from .utils import pass_context
  21. from .utils import pass_environment
  22. from .utils import pass_eval_context
  23. from .utils import pformat
  24. from .utils import url_quote
  25. from .utils import urlize
  26. if t.TYPE_CHECKING:
  27. import typing_extensions as te
  28. from .environment import Environment
  29. from .nodes import EvalContext
  30. from .runtime import Context
  31. from .sandbox import SandboxedEnvironment # noqa: F401
  32. class HasHTML(te.Protocol):
  33. def __html__(self) -> str:
  34. pass
  35. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  36. K = t.TypeVar("K")
  37. V = t.TypeVar("V")
  38. def ignore_case(value: V) -> V:
  39. """For use as a postprocessor for :func:`make_attrgetter`. Converts strings
  40. to lowercase and returns other types as-is."""
  41. if isinstance(value, str):
  42. return t.cast(V, value.lower())
  43. return value
  44. def make_attrgetter(
  45. environment: "Environment",
  46. attribute: t.Optional[t.Union[str, int]],
  47. postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
  48. default: t.Optional[t.Any] = None,
  49. ) -> t.Callable[[t.Any], t.Any]:
  50. """Returns a callable that looks up the given attribute from a
  51. passed object with the rules of the environment. Dots are allowed
  52. to access attributes of attributes. Integer parts in paths are
  53. looked up as integers.
  54. """
  55. parts = _prepare_attribute_parts(attribute)
  56. def attrgetter(item: t.Any) -> t.Any:
  57. for part in parts:
  58. item = environment.getitem(item, part)
  59. if default is not None and isinstance(item, Undefined):
  60. item = default
  61. if postprocess is not None:
  62. item = postprocess(item)
  63. return item
  64. return attrgetter
  65. def make_multi_attrgetter(
  66. environment: "Environment",
  67. attribute: t.Optional[t.Union[str, int]],
  68. postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
  69. ) -> t.Callable[[t.Any], t.List[t.Any]]:
  70. """Returns a callable that looks up the given comma separated
  71. attributes from a passed object with the rules of the environment.
  72. Dots are allowed to access attributes of each attribute. Integer
  73. parts in paths are looked up as integers.
  74. The value returned by the returned callable is a list of extracted
  75. attribute values.
  76. Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.
  77. """
  78. if isinstance(attribute, str):
  79. split: t.Sequence[t.Union[str, int, None]] = attribute.split(",")
  80. else:
  81. split = [attribute]
  82. parts = [_prepare_attribute_parts(item) for item in split]
  83. def attrgetter(item: t.Any) -> t.List[t.Any]:
  84. items = [None] * len(parts)
  85. for i, attribute_part in enumerate(parts):
  86. item_i = item
  87. for part in attribute_part:
  88. item_i = environment.getitem(item_i, part)
  89. if postprocess is not None:
  90. item_i = postprocess(item_i)
  91. items[i] = item_i
  92. return items
  93. return attrgetter
  94. def _prepare_attribute_parts(
  95. attr: t.Optional[t.Union[str, int]]
  96. ) -> t.List[t.Union[str, int]]:
  97. if attr is None:
  98. return []
  99. if isinstance(attr, str):
  100. return [int(x) if x.isdigit() else x for x in attr.split(".")]
  101. return [attr]
  102. def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup:
  103. """Enforce HTML escaping. This will probably double escape variables."""
  104. if hasattr(value, "__html__"):
  105. value = t.cast("HasHTML", value).__html__()
  106. return escape(str(value))
  107. def do_urlencode(
  108. value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]]
  109. ) -> str:
  110. """Quote data for use in a URL path or query using UTF-8.
  111. Basic wrapper around :func:`urllib.parse.quote` when given a
  112. string, or :func:`urllib.parse.urlencode` for a dict or iterable.
  113. :param value: Data to quote. A string will be quoted directly. A
  114. dict or iterable of ``(key, value)`` pairs will be joined as a
  115. query string.
  116. When given a string, "/" is not quoted. HTTP servers treat "/" and
  117. "%2F" equivalently in paths. If you need quoted slashes, use the
  118. ``|replace("/", "%2F")`` filter.
  119. .. versionadded:: 2.7
  120. """
  121. if isinstance(value, str) or not isinstance(value, abc.Iterable):
  122. return url_quote(value)
  123. if isinstance(value, dict):
  124. items: t.Iterable[t.Tuple[str, t.Any]] = value.items()
  125. else:
  126. items = value # type: ignore
  127. return "&".join(
  128. f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items
  129. )
  130. @pass_eval_context
  131. def do_replace(
  132. eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None
  133. ) -> str:
  134. """Return a copy of the value with all occurrences of a substring
  135. replaced with a new one. The first argument is the substring
  136. that should be replaced, the second is the replacement string.
  137. If the optional third argument ``count`` is given, only the first
  138. ``count`` occurrences are replaced:
  139. .. sourcecode:: jinja
  140. {{ "Hello World"|replace("Hello", "Goodbye") }}
  141. -> Goodbye World
  142. {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
  143. -> d'oh, d'oh, aaargh
  144. """
  145. if count is None:
  146. count = -1
  147. if not eval_ctx.autoescape:
  148. return str(s).replace(str(old), str(new), count)
  149. if (
  150. hasattr(old, "__html__")
  151. or hasattr(new, "__html__")
  152. and not hasattr(s, "__html__")
  153. ):
  154. s = escape(s)
  155. else:
  156. s = soft_str(s)
  157. return s.replace(soft_str(old), soft_str(new), count)
  158. def do_upper(s: str) -> str:
  159. """Convert a value to uppercase."""
  160. return soft_str(s).upper()
  161. def do_lower(s: str) -> str:
  162. """Convert a value to lowercase."""
  163. return soft_str(s).lower()
  164. def do_items(value: t.Union[t.Mapping[K, V], Undefined]) -> t.Iterator[t.Tuple[K, V]]:
  165. """Return an iterator over the ``(key, value)`` items of a mapping.
  166. ``x|items`` is the same as ``x.items()``, except if ``x`` is
  167. undefined an empty iterator is returned.
  168. This filter is useful if you expect the template to be rendered with
  169. an implementation of Jinja in another programming language that does
  170. not have a ``.items()`` method on its mapping type.
  171. .. code-block:: html+jinja
  172. <dl>
  173. {% for key, value in my_dict|items %}
  174. <dt>{{ key }}
  175. <dd>{{ value }}
  176. {% endfor %}
  177. </dl>
  178. .. versionadded:: 3.1
  179. """
  180. if isinstance(value, Undefined):
  181. return
  182. if not isinstance(value, abc.Mapping):
  183. raise TypeError("Can only get item pairs from a mapping.")
  184. yield from value.items()
  185. @pass_eval_context
  186. def do_xmlattr(
  187. eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True
  188. ) -> str:
  189. """Create an SGML/XML attribute string based on the items in a dict.
  190. All values that are neither `none` nor `undefined` are automatically
  191. escaped:
  192. .. sourcecode:: html+jinja
  193. <ul{{ {'class': 'my_list', 'missing': none,
  194. 'id': 'list-%d'|format(variable)}|xmlattr }}>
  195. ...
  196. </ul>
  197. Results in something like this:
  198. .. sourcecode:: html
  199. <ul class="my_list" id="list-42">
  200. ...
  201. </ul>
  202. As you can see it automatically prepends a space in front of the item
  203. if the filter returned something unless the second parameter is false.
  204. """
  205. rv = " ".join(
  206. f'{escape(key)}="{escape(value)}"'
  207. for key, value in d.items()
  208. if value is not None and not isinstance(value, Undefined)
  209. )
  210. if autospace and rv:
  211. rv = " " + rv
  212. if eval_ctx.autoescape:
  213. rv = Markup(rv)
  214. return rv
  215. def do_capitalize(s: str) -> str:
  216. """Capitalize a value. The first character will be uppercase, all others
  217. lowercase.
  218. """
  219. return soft_str(s).capitalize()
  220. _word_beginning_split_re = re.compile(r"([-\s({\[<]+)")
  221. def do_title(s: str) -> str:
  222. """Return a titlecased version of the value. I.e. words will start with
  223. uppercase letters, all remaining characters are lowercase.
  224. """
  225. return "".join(
  226. [
  227. item[0].upper() + item[1:].lower()
  228. for item in _word_beginning_split_re.split(soft_str(s))
  229. if item
  230. ]
  231. )
  232. def do_dictsort(
  233. value: t.Mapping[K, V],
  234. case_sensitive: bool = False,
  235. by: 'te.Literal["key", "value"]' = "key",
  236. reverse: bool = False,
  237. ) -> t.List[t.Tuple[K, V]]:
  238. """Sort a dict and yield (key, value) pairs. Python dicts may not
  239. be in the order you want to display them in, so sort them first.
  240. .. sourcecode:: jinja
  241. {% for key, value in mydict|dictsort %}
  242. sort the dict by key, case insensitive
  243. {% for key, value in mydict|dictsort(reverse=true) %}
  244. sort the dict by key, case insensitive, reverse order
  245. {% for key, value in mydict|dictsort(true) %}
  246. sort the dict by key, case sensitive
  247. {% for key, value in mydict|dictsort(false, 'value') %}
  248. sort the dict by value, case insensitive
  249. """
  250. if by == "key":
  251. pos = 0
  252. elif by == "value":
  253. pos = 1
  254. else:
  255. raise FilterArgumentError('You can only sort by either "key" or "value"')
  256. def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any:
  257. value = item[pos]
  258. if not case_sensitive:
  259. value = ignore_case(value)
  260. return value
  261. return sorted(value.items(), key=sort_func, reverse=reverse)
  262. @pass_environment
  263. def do_sort(
  264. environment: "Environment",
  265. value: "t.Iterable[V]",
  266. reverse: bool = False,
  267. case_sensitive: bool = False,
  268. attribute: t.Optional[t.Union[str, int]] = None,
  269. ) -> "t.List[V]":
  270. """Sort an iterable using Python's :func:`sorted`.
  271. .. sourcecode:: jinja
  272. {% for city in cities|sort %}
  273. ...
  274. {% endfor %}
  275. :param reverse: Sort descending instead of ascending.
  276. :param case_sensitive: When sorting strings, sort upper and lower
  277. case separately.
  278. :param attribute: When sorting objects or dicts, an attribute or
  279. key to sort by. Can use dot notation like ``"address.city"``.
  280. Can be a list of attributes like ``"age,name"``.
  281. The sort is stable, it does not change the relative order of
  282. elements that compare equal. This makes it is possible to chain
  283. sorts on different attributes and ordering.
  284. .. sourcecode:: jinja
  285. {% for user in users|sort(attribute="name")
  286. |sort(reverse=true, attribute="age") %}
  287. ...
  288. {% endfor %}
  289. As a shortcut to chaining when the direction is the same for all
  290. attributes, pass a comma separate list of attributes.
  291. .. sourcecode:: jinja
  292. {% for user in users|sort(attribute="age,name") %}
  293. ...
  294. {% endfor %}
  295. .. versionchanged:: 2.11.0
  296. The ``attribute`` parameter can be a comma separated list of
  297. attributes, e.g. ``"age,name"``.
  298. .. versionchanged:: 2.6
  299. The ``attribute`` parameter was added.
  300. """
  301. key_func = make_multi_attrgetter(
  302. environment, attribute, postprocess=ignore_case if not case_sensitive else None
  303. )
  304. return sorted(value, key=key_func, reverse=reverse)
  305. @pass_environment
  306. def do_unique(
  307. environment: "Environment",
  308. value: "t.Iterable[V]",
  309. case_sensitive: bool = False,
  310. attribute: t.Optional[t.Union[str, int]] = None,
  311. ) -> "t.Iterator[V]":
  312. """Returns a list of unique items from the given iterable.
  313. .. sourcecode:: jinja
  314. {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}
  315. -> ['foo', 'bar', 'foobar']
  316. The unique items are yielded in the same order as their first occurrence in
  317. the iterable passed to the filter.
  318. :param case_sensitive: Treat upper and lower case strings as distinct.
  319. :param attribute: Filter objects with unique values for this attribute.
  320. """
  321. getter = make_attrgetter(
  322. environment, attribute, postprocess=ignore_case if not case_sensitive else None
  323. )
  324. seen = set()
  325. for item in value:
  326. key = getter(item)
  327. if key not in seen:
  328. seen.add(key)
  329. yield item
  330. def _min_or_max(
  331. environment: "Environment",
  332. value: "t.Iterable[V]",
  333. func: "t.Callable[..., V]",
  334. case_sensitive: bool,
  335. attribute: t.Optional[t.Union[str, int]],
  336. ) -> "t.Union[V, Undefined]":
  337. it = iter(value)
  338. try:
  339. first = next(it)
  340. except StopIteration:
  341. return environment.undefined("No aggregated item, sequence was empty.")
  342. key_func = make_attrgetter(
  343. environment, attribute, postprocess=ignore_case if not case_sensitive else None
  344. )
  345. return func(chain([first], it), key=key_func)
  346. @pass_environment
  347. def do_min(
  348. environment: "Environment",
  349. value: "t.Iterable[V]",
  350. case_sensitive: bool = False,
  351. attribute: t.Optional[t.Union[str, int]] = None,
  352. ) -> "t.Union[V, Undefined]":
  353. """Return the smallest item from the sequence.
  354. .. sourcecode:: jinja
  355. {{ [1, 2, 3]|min }}
  356. -> 1
  357. :param case_sensitive: Treat upper and lower case strings as distinct.
  358. :param attribute: Get the object with the min value of this attribute.
  359. """
  360. return _min_or_max(environment, value, min, case_sensitive, attribute)
  361. @pass_environment
  362. def do_max(
  363. environment: "Environment",
  364. value: "t.Iterable[V]",
  365. case_sensitive: bool = False,
  366. attribute: t.Optional[t.Union[str, int]] = None,
  367. ) -> "t.Union[V, Undefined]":
  368. """Return the largest item from the sequence.
  369. .. sourcecode:: jinja
  370. {{ [1, 2, 3]|max }}
  371. -> 3
  372. :param case_sensitive: Treat upper and lower case strings as distinct.
  373. :param attribute: Get the object with the max value of this attribute.
  374. """
  375. return _min_or_max(environment, value, max, case_sensitive, attribute)
  376. def do_default(
  377. value: V,
  378. default_value: V = "", # type: ignore
  379. boolean: bool = False,
  380. ) -> V:
  381. """If the value is undefined it will return the passed default value,
  382. otherwise the value of the variable:
  383. .. sourcecode:: jinja
  384. {{ my_variable|default('my_variable is not defined') }}
  385. This will output the value of ``my_variable`` if the variable was
  386. defined, otherwise ``'my_variable is not defined'``. If you want
  387. to use default with variables that evaluate to false you have to
  388. set the second parameter to `true`:
  389. .. sourcecode:: jinja
  390. {{ ''|default('the string was empty', true) }}
  391. .. versionchanged:: 2.11
  392. It's now possible to configure the :class:`~jinja2.Environment` with
  393. :class:`~jinja2.ChainableUndefined` to make the `default` filter work
  394. on nested elements and attributes that may contain undefined values
  395. in the chain without getting an :exc:`~jinja2.UndefinedError`.
  396. """
  397. if isinstance(value, Undefined) or (boolean and not value):
  398. return default_value
  399. return value
  400. @pass_eval_context
  401. def sync_do_join(
  402. eval_ctx: "EvalContext",
  403. value: t.Iterable,
  404. d: str = "",
  405. attribute: t.Optional[t.Union[str, int]] = None,
  406. ) -> str:
  407. """Return a string which is the concatenation of the strings in the
  408. sequence. The separator between elements is an empty string per
  409. default, you can define it with the optional parameter:
  410. .. sourcecode:: jinja
  411. {{ [1, 2, 3]|join('|') }}
  412. -> 1|2|3
  413. {{ [1, 2, 3]|join }}
  414. -> 123
  415. It is also possible to join certain attributes of an object:
  416. .. sourcecode:: jinja
  417. {{ users|join(', ', attribute='username') }}
  418. .. versionadded:: 2.6
  419. The `attribute` parameter was added.
  420. """
  421. if attribute is not None:
  422. value = map(make_attrgetter(eval_ctx.environment, attribute), value)
  423. # no automatic escaping? joining is a lot easier then
  424. if not eval_ctx.autoescape:
  425. return str(d).join(map(str, value))
  426. # if the delimiter doesn't have an html representation we check
  427. # if any of the items has. If yes we do a coercion to Markup
  428. if not hasattr(d, "__html__"):
  429. value = list(value)
  430. do_escape = False
  431. for idx, item in enumerate(value):
  432. if hasattr(item, "__html__"):
  433. do_escape = True
  434. else:
  435. value[idx] = str(item)
  436. if do_escape:
  437. d = escape(d)
  438. else:
  439. d = str(d)
  440. return d.join(value)
  441. # no html involved, to normal joining
  442. return soft_str(d).join(map(soft_str, value))
  443. @async_variant(sync_do_join) # type: ignore
  444. async def do_join(
  445. eval_ctx: "EvalContext",
  446. value: t.Union[t.AsyncIterable, t.Iterable],
  447. d: str = "",
  448. attribute: t.Optional[t.Union[str, int]] = None,
  449. ) -> str:
  450. return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)
  451. def do_center(value: str, width: int = 80) -> str:
  452. """Centers the value in a field of a given width."""
  453. return soft_str(value).center(width)
  454. @pass_environment
  455. def sync_do_first(
  456. environment: "Environment", seq: "t.Iterable[V]"
  457. ) -> "t.Union[V, Undefined]":
  458. """Return the first item of a sequence."""
  459. try:
  460. return next(iter(seq))
  461. except StopIteration:
  462. return environment.undefined("No first item, sequence was empty.")
  463. @async_variant(sync_do_first) # type: ignore
  464. async def do_first(
  465. environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"
  466. ) -> "t.Union[V, Undefined]":
  467. try:
  468. return await auto_aiter(seq).__anext__()
  469. except StopAsyncIteration:
  470. return environment.undefined("No first item, sequence was empty.")
  471. @pass_environment
  472. def do_last(
  473. environment: "Environment", seq: "t.Reversible[V]"
  474. ) -> "t.Union[V, Undefined]":
  475. """Return the last item of a sequence.
  476. Note: Does not work with generators. You may want to explicitly
  477. convert it to a list:
  478. .. sourcecode:: jinja
  479. {{ data | selectattr('name', '==', 'Jinja') | list | last }}
  480. """
  481. try:
  482. return next(iter(reversed(seq)))
  483. except StopIteration:
  484. return environment.undefined("No last item, sequence was empty.")
  485. # No async do_last, it may not be safe in async mode.
  486. @pass_context
  487. def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":
  488. """Return a random item from the sequence."""
  489. try:
  490. return random.choice(seq)
  491. except IndexError:
  492. return context.environment.undefined("No random item, sequence was empty.")
  493. def do_filesizeformat(value: t.Union[str, float, int], binary: bool = False) -> str:
  494. """Format the value like a 'human-readable' file size (i.e. 13 kB,
  495. 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
  496. Giga, etc.), if the second parameter is set to `True` the binary
  497. prefixes are used (Mebi, Gibi).
  498. """
  499. bytes = float(value)
  500. base = 1024 if binary else 1000
  501. prefixes = [
  502. ("KiB" if binary else "kB"),
  503. ("MiB" if binary else "MB"),
  504. ("GiB" if binary else "GB"),
  505. ("TiB" if binary else "TB"),
  506. ("PiB" if binary else "PB"),
  507. ("EiB" if binary else "EB"),
  508. ("ZiB" if binary else "ZB"),
  509. ("YiB" if binary else "YB"),
  510. ]
  511. if bytes == 1:
  512. return "1 Byte"
  513. elif bytes < base:
  514. return f"{int(bytes)} Bytes"
  515. else:
  516. for i, prefix in enumerate(prefixes):
  517. unit = base ** (i + 2)
  518. if bytes < unit:
  519. return f"{base * bytes / unit:.1f} {prefix}"
  520. return f"{base * bytes / unit:.1f} {prefix}"
  521. def do_pprint(value: t.Any) -> str:
  522. """Pretty print a variable. Useful for debugging."""
  523. return pformat(value)
  524. _uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")
  525. @pass_eval_context
  526. def do_urlize(
  527. eval_ctx: "EvalContext",
  528. value: str,
  529. trim_url_limit: t.Optional[int] = None,
  530. nofollow: bool = False,
  531. target: t.Optional[str] = None,
  532. rel: t.Optional[str] = None,
  533. extra_schemes: t.Optional[t.Iterable[str]] = None,
  534. ) -> str:
  535. """Convert URLs in text into clickable links.
  536. This may not recognize links in some situations. Usually, a more
  537. comprehensive formatter, such as a Markdown library, is a better
  538. choice.
  539. Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
  540. addresses. Links with trailing punctuation (periods, commas, closing
  541. parentheses) and leading punctuation (opening parentheses) are
  542. recognized excluding the punctuation. Email addresses that include
  543. header fields are not recognized (for example,
  544. ``mailto:address@example.com?cc=copy@example.com``).
  545. :param value: Original text containing URLs to link.
  546. :param trim_url_limit: Shorten displayed URL values to this length.
  547. :param nofollow: Add the ``rel=nofollow`` attribute to links.
  548. :param target: Add the ``target`` attribute to links.
  549. :param rel: Add the ``rel`` attribute to links.
  550. :param extra_schemes: Recognize URLs that start with these schemes
  551. in addition to the default behavior. Defaults to
  552. ``env.policies["urlize.extra_schemes"]``, which defaults to no
  553. extra schemes.
  554. .. versionchanged:: 3.0
  555. The ``extra_schemes`` parameter was added.
  556. .. versionchanged:: 3.0
  557. Generate ``https://`` links for URLs without a scheme.
  558. .. versionchanged:: 3.0
  559. The parsing rules were updated. Recognize email addresses with
  560. or without the ``mailto:`` scheme. Validate IP addresses. Ignore
  561. parentheses and brackets in more cases.
  562. .. versionchanged:: 2.8
  563. The ``target`` parameter was added.
  564. """
  565. policies = eval_ctx.environment.policies
  566. rel_parts = set((rel or "").split())
  567. if nofollow:
  568. rel_parts.add("nofollow")
  569. rel_parts.update((policies["urlize.rel"] or "").split())
  570. rel = " ".join(sorted(rel_parts)) or None
  571. if target is None:
  572. target = policies["urlize.target"]
  573. if extra_schemes is None:
  574. extra_schemes = policies["urlize.extra_schemes"] or ()
  575. for scheme in extra_schemes:
  576. if _uri_scheme_re.fullmatch(scheme) is None:
  577. raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.")
  578. rv = urlize(
  579. value,
  580. trim_url_limit=trim_url_limit,
  581. rel=rel,
  582. target=target,
  583. extra_schemes=extra_schemes,
  584. )
  585. if eval_ctx.autoescape:
  586. rv = Markup(rv)
  587. return rv
  588. def do_indent(
  589. s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False
  590. ) -> str:
  591. """Return a copy of the string with each line indented by 4 spaces. The
  592. first line and blank lines are not indented by default.
  593. :param width: Number of spaces, or a string, to indent by.
  594. :param first: Don't skip indenting the first line.
  595. :param blank: Don't skip indenting empty lines.
  596. .. versionchanged:: 3.0
  597. ``width`` can be a string.
  598. .. versionchanged:: 2.10
  599. Blank lines are not indented by default.
  600. Rename the ``indentfirst`` argument to ``first``.
  601. """
  602. if isinstance(width, str):
  603. indention = width
  604. else:
  605. indention = " " * width
  606. newline = "\n"
  607. if isinstance(s, Markup):
  608. indention = Markup(indention)
  609. newline = Markup(newline)
  610. s += newline # this quirk is necessary for splitlines method
  611. if blank:
  612. rv = (newline + indention).join(s.splitlines())
  613. else:
  614. lines = s.splitlines()
  615. rv = lines.pop(0)
  616. if lines:
  617. rv += newline + newline.join(
  618. indention + line if line else line for line in lines
  619. )
  620. if first:
  621. rv = indention + rv
  622. return rv
  623. @pass_environment
  624. def do_truncate(
  625. env: "Environment",
  626. s: str,
  627. length: int = 255,
  628. killwords: bool = False,
  629. end: str = "...",
  630. leeway: t.Optional[int] = None,
  631. ) -> str:
  632. """Return a truncated copy of the string. The length is specified
  633. with the first parameter which defaults to ``255``. If the second
  634. parameter is ``true`` the filter will cut the text at length. Otherwise
  635. it will discard the last word. If the text was in fact
  636. truncated it will append an ellipsis sign (``"..."``). If you want a
  637. different ellipsis sign than ``"..."`` you can specify it using the
  638. third parameter. Strings that only exceed the length by the tolerance
  639. margin given in the fourth parameter will not be truncated.
  640. .. sourcecode:: jinja
  641. {{ "foo bar baz qux"|truncate(9) }}
  642. -> "foo..."
  643. {{ "foo bar baz qux"|truncate(9, True) }}
  644. -> "foo ba..."
  645. {{ "foo bar baz qux"|truncate(11) }}
  646. -> "foo bar baz qux"
  647. {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
  648. -> "foo bar..."
  649. The default leeway on newer Jinja versions is 5 and was 0 before but
  650. can be reconfigured globally.
  651. """
  652. if leeway is None:
  653. leeway = env.policies["truncate.leeway"]
  654. assert length >= len(end), f"expected length >= {len(end)}, got {length}"
  655. assert leeway >= 0, f"expected leeway >= 0, got {leeway}"
  656. if len(s) <= length + leeway:
  657. return s
  658. if killwords:
  659. return s[: length - len(end)] + end
  660. result = s[: length - len(end)].rsplit(" ", 1)[0]
  661. return result + end
  662. @pass_environment
  663. def do_wordwrap(
  664. environment: "Environment",
  665. s: str,
  666. width: int = 79,
  667. break_long_words: bool = True,
  668. wrapstring: t.Optional[str] = None,
  669. break_on_hyphens: bool = True,
  670. ) -> str:
  671. """Wrap a string to the given width. Existing newlines are treated
  672. as paragraphs to be wrapped separately.
  673. :param s: Original text to wrap.
  674. :param width: Maximum length of wrapped lines.
  675. :param break_long_words: If a word is longer than ``width``, break
  676. it across lines.
  677. :param break_on_hyphens: If a word contains hyphens, it may be split
  678. across lines.
  679. :param wrapstring: String to join each wrapped line. Defaults to
  680. :attr:`Environment.newline_sequence`.
  681. .. versionchanged:: 2.11
  682. Existing newlines are treated as paragraphs wrapped separately.
  683. .. versionchanged:: 2.11
  684. Added the ``break_on_hyphens`` parameter.
  685. .. versionchanged:: 2.7
  686. Added the ``wrapstring`` parameter.
  687. """
  688. import textwrap
  689. if wrapstring is None:
  690. wrapstring = environment.newline_sequence
  691. # textwrap.wrap doesn't consider existing newlines when wrapping.
  692. # If the string has a newline before width, wrap will still insert
  693. # a newline at width, resulting in a short line. Instead, split and
  694. # wrap each paragraph individually.
  695. return wrapstring.join(
  696. [
  697. wrapstring.join(
  698. textwrap.wrap(
  699. line,
  700. width=width,
  701. expand_tabs=False,
  702. replace_whitespace=False,
  703. break_long_words=break_long_words,
  704. break_on_hyphens=break_on_hyphens,
  705. )
  706. )
  707. for line in s.splitlines()
  708. ]
  709. )
  710. _word_re = re.compile(r"\w+")
  711. def do_wordcount(s: str) -> int:
  712. """Count the words in that string."""
  713. return len(_word_re.findall(soft_str(s)))
  714. def do_int(value: t.Any, default: int = 0, base: int = 10) -> int:
  715. """Convert the value into an integer. If the
  716. conversion doesn't work it will return ``0``. You can
  717. override this default using the first parameter. You
  718. can also override the default base (10) in the second
  719. parameter, which handles input with prefixes such as
  720. 0b, 0o and 0x for bases 2, 8 and 16 respectively.
  721. The base is ignored for decimal numbers and non-string values.
  722. """
  723. try:
  724. if isinstance(value, str):
  725. return int(value, base)
  726. return int(value)
  727. except (TypeError, ValueError):
  728. # this quirk is necessary so that "42.23"|int gives 42.
  729. try:
  730. return int(float(value))
  731. except (TypeError, ValueError):
  732. return default
  733. def do_float(value: t.Any, default: float = 0.0) -> float:
  734. """Convert the value into a floating point number. If the
  735. conversion doesn't work it will return ``0.0``. You can
  736. override this default using the first parameter.
  737. """
  738. try:
  739. return float(value)
  740. except (TypeError, ValueError):
  741. return default
  742. def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:
  743. """Apply the given values to a `printf-style`_ format string, like
  744. ``string % values``.
  745. .. sourcecode:: jinja
  746. {{ "%s, %s!"|format(greeting, name) }}
  747. Hello, World!
  748. In most cases it should be more convenient and efficient to use the
  749. ``%`` operator or :meth:`str.format`.
  750. .. code-block:: text
  751. {{ "%s, %s!" % (greeting, name) }}
  752. {{ "{}, {}!".format(greeting, name) }}
  753. .. _printf-style: https://docs.python.org/library/stdtypes.html
  754. #printf-style-string-formatting
  755. """
  756. if args and kwargs:
  757. raise FilterArgumentError(
  758. "can't handle positional and keyword arguments at the same time"
  759. )
  760. return soft_str(value) % (kwargs or args)
  761. def do_trim(value: str, chars: t.Optional[str] = None) -> str:
  762. """Strip leading and trailing characters, by default whitespace."""
  763. return soft_str(value).strip(chars)
  764. def do_striptags(value: "t.Union[str, HasHTML]") -> str:
  765. """Strip SGML/XML tags and replace adjacent whitespace by one space."""
  766. if hasattr(value, "__html__"):
  767. value = t.cast("HasHTML", value).__html__()
  768. return Markup(str(value)).striptags()
  769. def sync_do_slice(
  770. value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None
  771. ) -> "t.Iterator[t.List[V]]":
  772. """Slice an iterator and return a list of lists containing
  773. those items. Useful if you want to create a div containing
  774. three ul tags that represent columns:
  775. .. sourcecode:: html+jinja
  776. <div class="columnwrapper">
  777. {%- for column in items|slice(3) %}
  778. <ul class="column-{{ loop.index }}">
  779. {%- for item in column %}
  780. <li>{{ item }}</li>
  781. {%- endfor %}
  782. </ul>
  783. {%- endfor %}
  784. </div>
  785. If you pass it a second argument it's used to fill missing
  786. values on the last iteration.
  787. """
  788. seq = list(value)
  789. length = len(seq)
  790. items_per_slice = length // slices
  791. slices_with_extra = length % slices
  792. offset = 0
  793. for slice_number in range(slices):
  794. start = offset + slice_number * items_per_slice
  795. if slice_number < slices_with_extra:
  796. offset += 1
  797. end = offset + (slice_number + 1) * items_per_slice
  798. tmp = seq[start:end]
  799. if fill_with is not None and slice_number >= slices_with_extra:
  800. tmp.append(fill_with)
  801. yield tmp
  802. @async_variant(sync_do_slice) # type: ignore
  803. async def do_slice(
  804. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  805. slices: int,
  806. fill_with: t.Optional[t.Any] = None,
  807. ) -> "t.Iterator[t.List[V]]":
  808. return sync_do_slice(await auto_to_list(value), slices, fill_with)
  809. def do_batch(
  810. value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None
  811. ) -> "t.Iterator[t.List[V]]":
  812. """
  813. A filter that batches items. It works pretty much like `slice`
  814. just the other way round. It returns a list of lists with the
  815. given number of items. If you provide a second parameter this
  816. is used to fill up missing items. See this example:
  817. .. sourcecode:: html+jinja
  818. <table>
  819. {%- for row in items|batch(3, '&nbsp;') %}
  820. <tr>
  821. {%- for column in row %}
  822. <td>{{ column }}</td>
  823. {%- endfor %}
  824. </tr>
  825. {%- endfor %}
  826. </table>
  827. """
  828. tmp: "t.List[V]" = []
  829. for item in value:
  830. if len(tmp) == linecount:
  831. yield tmp
  832. tmp = []
  833. tmp.append(item)
  834. if tmp:
  835. if fill_with is not None and len(tmp) < linecount:
  836. tmp += [fill_with] * (linecount - len(tmp))
  837. yield tmp
  838. def do_round(
  839. value: float,
  840. precision: int = 0,
  841. method: 'te.Literal["common", "ceil", "floor"]' = "common",
  842. ) -> float:
  843. """Round the number to a given precision. The first
  844. parameter specifies the precision (default is ``0``), the
  845. second the rounding method:
  846. - ``'common'`` rounds either up or down
  847. - ``'ceil'`` always rounds up
  848. - ``'floor'`` always rounds down
  849. If you don't specify a method ``'common'`` is used.
  850. .. sourcecode:: jinja
  851. {{ 42.55|round }}
  852. -> 43.0
  853. {{ 42.55|round(1, 'floor') }}
  854. -> 42.5
  855. Note that even if rounded to 0 precision, a float is returned. If
  856. you need a real integer, pipe it through `int`:
  857. .. sourcecode:: jinja
  858. {{ 42.55|round|int }}
  859. -> 43
  860. """
  861. if method not in {"common", "ceil", "floor"}:
  862. raise FilterArgumentError("method must be common, ceil or floor")
  863. if method == "common":
  864. return round(value, precision)
  865. func = getattr(math, method)
  866. return t.cast(float, func(value * (10**precision)) / (10**precision))
  867. class _GroupTuple(t.NamedTuple):
  868. grouper: t.Any
  869. list: t.List
  870. # Use the regular tuple repr to hide this subclass if users print
  871. # out the value during debugging.
  872. def __repr__(self) -> str:
  873. return tuple.__repr__(self)
  874. def __str__(self) -> str:
  875. return tuple.__str__(self)
  876. @pass_environment
  877. def sync_do_groupby(
  878. environment: "Environment",
  879. value: "t.Iterable[V]",
  880. attribute: t.Union[str, int],
  881. default: t.Optional[t.Any] = None,
  882. case_sensitive: bool = False,
  883. ) -> "t.List[_GroupTuple]":
  884. """Group a sequence of objects by an attribute using Python's
  885. :func:`itertools.groupby`. The attribute can use dot notation for
  886. nested access, like ``"address.city"``. Unlike Python's ``groupby``,
  887. the values are sorted first so only one group is returned for each
  888. unique value.
  889. For example, a list of ``User`` objects with a ``city`` attribute
  890. can be rendered in groups. In this example, ``grouper`` refers to
  891. the ``city`` value of the group.
  892. .. sourcecode:: html+jinja
  893. <ul>{% for city, items in users|groupby("city") %}
  894. <li>{{ city }}
  895. <ul>{% for user in items %}
  896. <li>{{ user.name }}
  897. {% endfor %}</ul>
  898. </li>
  899. {% endfor %}</ul>
  900. ``groupby`` yields namedtuples of ``(grouper, list)``, which
  901. can be used instead of the tuple unpacking above. ``grouper`` is the
  902. value of the attribute, and ``list`` is the items with that value.
  903. .. sourcecode:: html+jinja
  904. <ul>{% for group in users|groupby("city") %}
  905. <li>{{ group.grouper }}: {{ group.list|join(", ") }}
  906. {% endfor %}</ul>
  907. You can specify a ``default`` value to use if an object in the list
  908. does not have the given attribute.
  909. .. sourcecode:: jinja
  910. <ul>{% for city, items in users|groupby("city", default="NY") %}
  911. <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
  912. {% endfor %}</ul>
  913. Like the :func:`~jinja-filters.sort` filter, sorting and grouping is
  914. case-insensitive by default. The ``key`` for each group will have
  915. the case of the first item in that group of values. For example, if
  916. a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group
  917. will have two values. This can be disabled by passing
  918. ``case_sensitive=True``.
  919. .. versionchanged:: 3.1
  920. Added the ``case_sensitive`` parameter. Sorting and grouping is
  921. case-insensitive by default, matching other filters that do
  922. comparisons.
  923. .. versionchanged:: 3.0
  924. Added the ``default`` parameter.
  925. .. versionchanged:: 2.6
  926. The attribute supports dot notation for nested access.
  927. """
  928. expr = make_attrgetter(
  929. environment,
  930. attribute,
  931. postprocess=ignore_case if not case_sensitive else None,
  932. default=default,
  933. )
  934. out = [
  935. _GroupTuple(key, list(values))
  936. for key, values in groupby(sorted(value, key=expr), expr)
  937. ]
  938. if not case_sensitive:
  939. # Return the real key from the first value instead of the lowercase key.
  940. output_expr = make_attrgetter(environment, attribute, default=default)
  941. out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
  942. return out
  943. @async_variant(sync_do_groupby) # type: ignore
  944. async def do_groupby(
  945. environment: "Environment",
  946. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  947. attribute: t.Union[str, int],
  948. default: t.Optional[t.Any] = None,
  949. case_sensitive: bool = False,
  950. ) -> "t.List[_GroupTuple]":
  951. expr = make_attrgetter(
  952. environment,
  953. attribute,
  954. postprocess=ignore_case if not case_sensitive else None,
  955. default=default,
  956. )
  957. out = [
  958. _GroupTuple(key, await auto_to_list(values))
  959. for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)
  960. ]
  961. if not case_sensitive:
  962. # Return the real key from the first value instead of the lowercase key.
  963. output_expr = make_attrgetter(environment, attribute, default=default)
  964. out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
  965. return out
  966. @pass_environment
  967. def sync_do_sum(
  968. environment: "Environment",
  969. iterable: "t.Iterable[V]",
  970. attribute: t.Optional[t.Union[str, int]] = None,
  971. start: V = 0, # type: ignore
  972. ) -> V:
  973. """Returns the sum of a sequence of numbers plus the value of parameter
  974. 'start' (which defaults to 0). When the sequence is empty it returns
  975. start.
  976. It is also possible to sum up only certain attributes:
  977. .. sourcecode:: jinja
  978. Total: {{ items|sum(attribute='price') }}
  979. .. versionchanged:: 2.6
  980. The ``attribute`` parameter was added to allow summing up over
  981. attributes. Also the ``start`` parameter was moved on to the right.
  982. """
  983. if attribute is not None:
  984. iterable = map(make_attrgetter(environment, attribute), iterable)
  985. return sum(iterable, start) # type: ignore[no-any-return, call-overload]
  986. @async_variant(sync_do_sum) # type: ignore
  987. async def do_sum(
  988. environment: "Environment",
  989. iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  990. attribute: t.Optional[t.Union[str, int]] = None,
  991. start: V = 0, # type: ignore
  992. ) -> V:
  993. rv = start
  994. if attribute is not None:
  995. func = make_attrgetter(environment, attribute)
  996. else:
  997. def func(x: V) -> V:
  998. return x
  999. async for item in auto_aiter(iterable):
  1000. rv += func(item)
  1001. return rv
  1002. def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]":
  1003. """Convert the value into a list. If it was a string the returned list
  1004. will be a list of characters.
  1005. """
  1006. return list(value)
  1007. @async_variant(sync_do_list) # type: ignore
  1008. async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":
  1009. return await auto_to_list(value)
  1010. def do_mark_safe(value: str) -> Markup:
  1011. """Mark the value as safe which means that in an environment with automatic
  1012. escaping enabled this variable will not be escaped.
  1013. """
  1014. return Markup(value)
  1015. def do_mark_unsafe(value: str) -> str:
  1016. """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
  1017. return str(value)
  1018. @typing.overload
  1019. def do_reverse(value: str) -> str:
  1020. ...
  1021. @typing.overload
  1022. def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":
  1023. ...
  1024. def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:
  1025. """Reverse the object or return an iterator that iterates over it the other
  1026. way round.
  1027. """
  1028. if isinstance(value, str):
  1029. return value[::-1]
  1030. try:
  1031. return reversed(value) # type: ignore
  1032. except TypeError:
  1033. try:
  1034. rv = list(value)
  1035. rv.reverse()
  1036. return rv
  1037. except TypeError as e:
  1038. raise FilterArgumentError("argument must be iterable") from e
  1039. @pass_environment
  1040. def do_attr(
  1041. environment: "Environment", obj: t.Any, name: str
  1042. ) -> t.Union[Undefined, t.Any]:
  1043. """Get an attribute of an object. ``foo|attr("bar")`` works like
  1044. ``foo.bar`` just that always an attribute is returned and items are not
  1045. looked up.
  1046. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
  1047. """
  1048. try:
  1049. name = str(name)
  1050. except UnicodeError:
  1051. pass
  1052. else:
  1053. try:
  1054. value = getattr(obj, name)
  1055. except AttributeError:
  1056. pass
  1057. else:
  1058. if environment.sandboxed:
  1059. environment = t.cast("SandboxedEnvironment", environment)
  1060. if not environment.is_safe_attribute(obj, name, value):
  1061. return environment.unsafe_undefined(obj, name)
  1062. return value
  1063. return environment.undefined(obj=obj, name=name)
  1064. @typing.overload
  1065. def sync_do_map(
  1066. context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any
  1067. ) -> t.Iterable:
  1068. ...
  1069. @typing.overload
  1070. def sync_do_map(
  1071. context: "Context",
  1072. value: t.Iterable,
  1073. *,
  1074. attribute: str = ...,
  1075. default: t.Optional[t.Any] = None,
  1076. ) -> t.Iterable:
  1077. ...
  1078. @pass_context
  1079. def sync_do_map(
  1080. context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any
  1081. ) -> t.Iterable:
  1082. """Applies a filter on a sequence of objects or looks up an attribute.
  1083. This is useful when dealing with lists of objects but you are really
  1084. only interested in a certain value of it.
  1085. The basic usage is mapping on an attribute. Imagine you have a list
  1086. of users but you are only interested in a list of usernames:
  1087. .. sourcecode:: jinja
  1088. Users on this page: {{ users|map(attribute='username')|join(', ') }}
  1089. You can specify a ``default`` value to use if an object in the list
  1090. does not have the given attribute.
  1091. .. sourcecode:: jinja
  1092. {{ users|map(attribute="username", default="Anonymous")|join(", ") }}
  1093. Alternatively you can let it invoke a filter by passing the name of the
  1094. filter and the arguments afterwards. A good example would be applying a
  1095. text conversion filter on a sequence:
  1096. .. sourcecode:: jinja
  1097. Users on this page: {{ titles|map('lower')|join(', ') }}
  1098. Similar to a generator comprehension such as:
  1099. .. code-block:: python
  1100. (u.username for u in users)
  1101. (getattr(u, "username", "Anonymous") for u in users)
  1102. (do_lower(x) for x in titles)
  1103. .. versionchanged:: 2.11.0
  1104. Added the ``default`` parameter.
  1105. .. versionadded:: 2.7
  1106. """
  1107. if value:
  1108. func = prepare_map(context, args, kwargs)
  1109. for item in value:
  1110. yield func(item)
  1111. @typing.overload
  1112. def do_map(
  1113. context: "Context",
  1114. value: t.Union[t.AsyncIterable, t.Iterable],
  1115. name: str,
  1116. *args: t.Any,
  1117. **kwargs: t.Any,
  1118. ) -> t.Iterable:
  1119. ...
  1120. @typing.overload
  1121. def do_map(
  1122. context: "Context",
  1123. value: t.Union[t.AsyncIterable, t.Iterable],
  1124. *,
  1125. attribute: str = ...,
  1126. default: t.Optional[t.Any] = None,
  1127. ) -> t.Iterable:
  1128. ...
  1129. @async_variant(sync_do_map) # type: ignore
  1130. async def do_map(
  1131. context: "Context",
  1132. value: t.Union[t.AsyncIterable, t.Iterable],
  1133. *args: t.Any,
  1134. **kwargs: t.Any,
  1135. ) -> t.AsyncIterable:
  1136. if value:
  1137. func = prepare_map(context, args, kwargs)
  1138. async for item in auto_aiter(value):
  1139. yield await auto_await(func(item))
  1140. @pass_context
  1141. def sync_do_select(
  1142. context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
  1143. ) -> "t.Iterator[V]":
  1144. """Filters a sequence of objects by applying a test to each object,
  1145. and only selecting the objects with the test succeeding.
  1146. If no test is specified, each object will be evaluated as a boolean.
  1147. Example usage:
  1148. .. sourcecode:: jinja
  1149. {{ numbers|select("odd") }}
  1150. {{ numbers|select("odd") }}
  1151. {{ numbers|select("divisibleby", 3) }}
  1152. {{ numbers|select("lessthan", 42) }}
  1153. {{ strings|select("equalto", "mystring") }}
  1154. Similar to a generator comprehension such as:
  1155. .. code-block:: python
  1156. (n for n in numbers if test_odd(n))
  1157. (n for n in numbers if test_divisibleby(n, 3))
  1158. .. versionadded:: 2.7
  1159. """
  1160. return select_or_reject(context, value, args, kwargs, lambda x: x, False)
  1161. @async_variant(sync_do_select) # type: ignore
  1162. async def do_select(
  1163. context: "Context",
  1164. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1165. *args: t.Any,
  1166. **kwargs: t.Any,
  1167. ) -> "t.AsyncIterator[V]":
  1168. return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)
  1169. @pass_context
  1170. def sync_do_reject(
  1171. context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
  1172. ) -> "t.Iterator[V]":
  1173. """Filters a sequence of objects by applying a test to each object,
  1174. and rejecting the objects with the test succeeding.
  1175. If no test is specified, each object will be evaluated as a boolean.
  1176. Example usage:
  1177. .. sourcecode:: jinja
  1178. {{ numbers|reject("odd") }}
  1179. Similar to a generator comprehension such as:
  1180. .. code-block:: python
  1181. (n for n in numbers if not test_odd(n))
  1182. .. versionadded:: 2.7
  1183. """
  1184. return select_or_reject(context, value, args, kwargs, lambda x: not x, False)
  1185. @async_variant(sync_do_reject) # type: ignore
  1186. async def do_reject(
  1187. context: "Context",
  1188. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1189. *args: t.Any,
  1190. **kwargs: t.Any,
  1191. ) -> "t.AsyncIterator[V]":
  1192. return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)
  1193. @pass_context
  1194. def sync_do_selectattr(
  1195. context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
  1196. ) -> "t.Iterator[V]":
  1197. """Filters a sequence of objects by applying a test to the specified
  1198. attribute of each object, and only selecting the objects with the
  1199. test succeeding.
  1200. If no test is specified, the attribute's value will be evaluated as
  1201. a boolean.
  1202. Example usage:
  1203. .. sourcecode:: jinja
  1204. {{ users|selectattr("is_active") }}
  1205. {{ users|selectattr("email", "none") }}
  1206. Similar to a generator comprehension such as:
  1207. .. code-block:: python
  1208. (u for user in users if user.is_active)
  1209. (u for user in users if test_none(user.email))
  1210. .. versionadded:: 2.7
  1211. """
  1212. return select_or_reject(context, value, args, kwargs, lambda x: x, True)
  1213. @async_variant(sync_do_selectattr) # type: ignore
  1214. async def do_selectattr(
  1215. context: "Context",
  1216. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1217. *args: t.Any,
  1218. **kwargs: t.Any,
  1219. ) -> "t.AsyncIterator[V]":
  1220. return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)
  1221. @pass_context
  1222. def sync_do_rejectattr(
  1223. context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
  1224. ) -> "t.Iterator[V]":
  1225. """Filters a sequence of objects by applying a test to the specified
  1226. attribute of each object, and rejecting the objects with the test
  1227. succeeding.
  1228. If no test is specified, the attribute's value will be evaluated as
  1229. a boolean.
  1230. .. sourcecode:: jinja
  1231. {{ users|rejectattr("is_active") }}
  1232. {{ users|rejectattr("email", "none") }}
  1233. Similar to a generator comprehension such as:
  1234. .. code-block:: python
  1235. (u for user in users if not user.is_active)
  1236. (u for user in users if not test_none(user.email))
  1237. .. versionadded:: 2.7
  1238. """
  1239. return select_or_reject(context, value, args, kwargs, lambda x: not x, True)
  1240. @async_variant(sync_do_rejectattr) # type: ignore
  1241. async def do_rejectattr(
  1242. context: "Context",
  1243. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1244. *args: t.Any,
  1245. **kwargs: t.Any,
  1246. ) -> "t.AsyncIterator[V]":
  1247. return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)
  1248. @pass_eval_context
  1249. def do_tojson(
  1250. eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
  1251. ) -> Markup:
  1252. """Serialize an object to a string of JSON, and mark it safe to
  1253. render in HTML. This filter is only for use in HTML documents.
  1254. The returned string is safe to render in HTML documents and
  1255. ``<script>`` tags. The exception is in HTML attributes that are
  1256. double quoted; either use single quotes or the ``|forceescape``
  1257. filter.
  1258. :param value: The object to serialize to JSON.
  1259. :param indent: The ``indent`` parameter passed to ``dumps``, for
  1260. pretty-printing the value.
  1261. .. versionadded:: 2.9
  1262. """
  1263. policies = eval_ctx.environment.policies
  1264. dumps = policies["json.dumps_function"]
  1265. kwargs = policies["json.dumps_kwargs"]
  1266. if indent is not None:
  1267. kwargs = kwargs.copy()
  1268. kwargs["indent"] = indent
  1269. return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)
  1270. def prepare_map(
  1271. context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]
  1272. ) -> t.Callable[[t.Any], t.Any]:
  1273. if not args and "attribute" in kwargs:
  1274. attribute = kwargs.pop("attribute")
  1275. default = kwargs.pop("default", None)
  1276. if kwargs:
  1277. raise FilterArgumentError(
  1278. f"Unexpected keyword argument {next(iter(kwargs))!r}"
  1279. )
  1280. func = make_attrgetter(context.environment, attribute, default=default)
  1281. else:
  1282. try:
  1283. name = args[0]
  1284. args = args[1:]
  1285. except LookupError:
  1286. raise FilterArgumentError("map requires a filter argument") from None
  1287. def func(item: t.Any) -> t.Any:
  1288. return context.environment.call_filter(
  1289. name, item, args, kwargs, context=context
  1290. )
  1291. return func
  1292. def prepare_select_or_reject(
  1293. context: "Context",
  1294. args: t.Tuple,
  1295. kwargs: t.Dict[str, t.Any],
  1296. modfunc: t.Callable[[t.Any], t.Any],
  1297. lookup_attr: bool,
  1298. ) -> t.Callable[[t.Any], t.Any]:
  1299. if lookup_attr:
  1300. try:
  1301. attr = args[0]
  1302. except LookupError:
  1303. raise FilterArgumentError("Missing parameter for attribute name") from None
  1304. transfunc = make_attrgetter(context.environment, attr)
  1305. off = 1
  1306. else:
  1307. off = 0
  1308. def transfunc(x: V) -> V:
  1309. return x
  1310. try:
  1311. name = args[off]
  1312. args = args[1 + off :]
  1313. def func(item: t.Any) -> t.Any:
  1314. return context.environment.call_test(name, item, args, kwargs)
  1315. except LookupError:
  1316. func = bool # type: ignore
  1317. return lambda item: modfunc(func(transfunc(item)))
  1318. def select_or_reject(
  1319. context: "Context",
  1320. value: "t.Iterable[V]",
  1321. args: t.Tuple,
  1322. kwargs: t.Dict[str, t.Any],
  1323. modfunc: t.Callable[[t.Any], t.Any],
  1324. lookup_attr: bool,
  1325. ) -> "t.Iterator[V]":
  1326. if value:
  1327. func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
  1328. for item in value:
  1329. if func(item):
  1330. yield item
  1331. async def async_select_or_reject(
  1332. context: "Context",
  1333. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1334. args: t.Tuple,
  1335. kwargs: t.Dict[str, t.Any],
  1336. modfunc: t.Callable[[t.Any], t.Any],
  1337. lookup_attr: bool,
  1338. ) -> "t.AsyncIterator[V]":
  1339. if value:
  1340. func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
  1341. async for item in auto_aiter(value):
  1342. if func(item):
  1343. yield item
  1344. FILTERS = {
  1345. "abs": abs,
  1346. "attr": do_attr,
  1347. "batch": do_batch,
  1348. "capitalize": do_capitalize,
  1349. "center": do_center,
  1350. "count": len,
  1351. "d": do_default,
  1352. "default": do_default,
  1353. "dictsort": do_dictsort,
  1354. "e": escape,
  1355. "escape": escape,
  1356. "filesizeformat": do_filesizeformat,
  1357. "first": do_first,
  1358. "float": do_float,
  1359. "forceescape": do_forceescape,
  1360. "format": do_format,
  1361. "groupby": do_groupby,
  1362. "indent": do_indent,
  1363. "int": do_int,
  1364. "join": do_join,
  1365. "last": do_last,
  1366. "length": len,
  1367. "list": do_list,
  1368. "lower": do_lower,
  1369. "items": do_items,
  1370. "map": do_map,
  1371. "min": do_min,
  1372. "max": do_max,
  1373. "pprint": do_pprint,
  1374. "random": do_random,
  1375. "reject": do_reject,
  1376. "rejectattr": do_rejectattr,
  1377. "replace": do_replace,
  1378. "reverse": do_reverse,
  1379. "round": do_round,
  1380. "safe": do_mark_safe,
  1381. "select": do_select,
  1382. "selectattr": do_selectattr,
  1383. "slice": do_slice,
  1384. "sort": do_sort,
  1385. "string": soft_str,
  1386. "striptags": do_striptags,
  1387. "sum": do_sum,
  1388. "title": do_title,
  1389. "trim": do_trim,
  1390. "truncate": do_truncate,
  1391. "unique": do_unique,
  1392. "upper": do_upper,
  1393. "urlencode": do_urlencode,
  1394. "urlize": do_urlize,
  1395. "wordcount": do_wordcount,
  1396. "wordwrap": do_wordwrap,
  1397. "xmlattr": do_xmlattr,
  1398. "tojson": do_tojson,
  1399. }